package com.example.test.util;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Base64;

/**
 * @Author 林文峰
 * @Date 2020/6/28 0028 11:18
 */
public class HtmlToWord {

	public static String htmlToWord(HttpServletRequest request, HttpServletResponse response){
		InputStream ins = null;
		StringBuilder content = new StringBuilder();
		StringBuilder result = new StringBuilder();
//		File file = new File("F:\\下载位置\\test1.html");
		try {
			int len = 0;
			//Html文件转为StringBuilder
			ins = new FileInputStream("F:\\下载位置\\test09.html");
			byte[] bytes = new byte[1024];
			while((len = ins.read(bytes)) != -1){
				content.append(new String(bytes,0,len));
			}
			ins.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String temp = content.toString();
		//切割获取base64格式图片，并解码储存
		String[] split = temp.split("data");
		for (int i = 0;i < split.length;i++) {
			String s = split[i];
			System.out.println(s);
			if (s.contains("base64,")){
				String str = s.substring(s.indexOf(",")+1, s.indexOf("\""));
//				System.out.println(str);
//				s = s.replace(s.substring(0, s.indexOf("\"")),"");
				Base64.Decoder decoder = Base64.getDecoder();
			    byte[] decode = decoder.decode(str);
				//转存图片
				String imgPath = imgSave(decode, "img" + i);
			    s = s.replace(s.substring(0, s.indexOf("\"")),imgPath);
			}
			result.append(s);
		}
		String filePath = exportWord(request,response,result.toString());
//		String filePath = exportWord(request,response,result.toString());
//		String filePath = downloadWordReport(result.toString());
		return filePath;
	}
	
	private static String imgSave(byte[] img,String fileName){
		String filePath = "G:\\上传测试\\img\\";
		File f = new File(filePath+fileName+".jpg");
		try {
			OutputStream out = new FileOutputStream(f);
			out.write(img);
			CloseUtil.conClose(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filePath+fileName+".jpg";
	}
	
	//在工具类中的实现方法：
	private static String exportWord(HttpServletRequest request, HttpServletResponse response, String content){
		String path = "G:\\上传测试\\";
		String fileName = "ccc.doc";
//		String name =null;
		try {
			byte b[] = content.getBytes("GBK");  //这里是必须要设置编码的，不然导出中文就会乱码。
			ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
			//生成word
			POIFSFileSystem poifs = new POIFSFileSystem();
			DirectoryEntry directory = poifs.getRoot();
			DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
//			name = documentEntry.getName();
//			//输出文件
//			response.setCharacterEncoding("GBK");
//			//设置word格式
			response.setContentType("application/msword");
			response.setHeader("Content-disposition", "attachment;filename=exportWord.doc");
			response.addHeader("Content-Disposition", "p_w_upload;filename=" +
					new String((documentEntry.getName() + ".doc").getBytes(),  "UTF-8"));
			OutputStream ostream = response.getOutputStream();
//			File rootPath = new File("");
//			String name = "\\temp.doc";
//			File file = new File(rootPath.getCanonicalPath() + name);
//			FileInputStream ins = new FileInputStream(file);
//			HWPFDocument hwpfDocument = new HWPFDocument(ins);
//			Range range = hwpfDocument.getRange();
//			OutputStream ostream = new FileOutputStream(file);
//			FileOutputStream ostream = new FileOutputStream(path+ fileName);
//			File file1 = new File(path + fileName);
//			FileOutputStream fileOutputStream = new FileOutputStream(file1);
			poifs.writeFilesystem(ostream);
			bais.close();
			ostream.close();
		}catch(Exception e){
			//异常处理
			return null;
//			logger.error("文件导出错误", e);
		}
		return path+ fileName;
	}
	
//	/**
//	 * word格式html的标签头
//	 */
//	private static final String HTML_TAG_BGN = "<html xmlns=\"http://www.w3.org/TR/REC-html40\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"><head><meta name=\"ProgId\" content=\"Word.Document\" /><meta name=\"Generator\" content=\"Microsoft Word 12\" /><meta name=\"Originator\" content=\"Microsoft Word 12\" /> <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View></w:WordDocument></xml><[endif]-->";
//
//
//	public static String downloadWordReport(String htmlForPrint) {
//		String path = "G:\\上传测试\\";
//		try {
//			String wordString = htmlForPrint.replaceAll("<head>", "").replaceAll("<html>", HTML_TAG_BGN );
//			String fileName = new String("测试文件.doc".getBytes(), "UTF-8");
//			FileOutputStream ostream = new FileOutputStream(path+ fileName);
//			//上传文件方法
//			
//			ostream.write(wordString.getBytes("UTF-8"));
//			ostream.close();
//		} catch (Exception e) {
//			return null;
//		}
//		return path;
//	}
	
}
